import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Jiang Jinxi
 * Date: 2024-09-02
 * Time: 13:17
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run(){
        runnable.run();
    }

    public long getTime(){
        return this.time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
        //return (int)(o.time - this.time);
    }
}
class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();//创建锁对象


    public MyTimer(){
        Thread thread = new Thread(() -> {
            try{
                while(true){
                    synchronized (locker){
                        //如果任务队列为空,就阻塞等待
                        if(queue.size() == 0){
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        //如果此时的时间 >= 要执行的任务的时间, 则执行任务, 并出队列,
                        // 反之则阻塞等待task.getTime() - curTime这些时间, 时间到了就执行任务
                        long curTime = System.currentTimeMillis();
                        if(task.getTime() <= curTime){
                            task.run();
                            queue.poll();
                        }else{
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable, long delay){
       synchronized (locker){
           MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
           queue.offer(myTimerTask);
           locker.notify();
       }
    }
}
public class Demo30 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        //可以设多个定时器
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
    }
}
